home *** CD-ROM | disk | FTP | other *** search
/ PC World 2008 February (DVD) / PCWorld_2008-02_DVD.iso / v cisle / PHP / PHP.exe / EasyPHP-2.0b1-setup.exe / {app} / phpmyadmin / libraries / Table.class.php < prev    next >
Encoding:
PHP Script  |  2006-11-18  |  38.9 KB  |  980 lines

  1. <?php
  2.  
  3.  
  4. class PMA_Table {
  5.  
  6.     /**
  7.      * @var string  table name
  8.      */
  9.     var $name = '';
  10.  
  11.     /**
  12.      * @var string  database name
  13.      */
  14.     var $db_name = '';
  15.  
  16.     /**
  17.      * @var string  engine (innodb, myisam, bdb, ...)
  18.      */
  19.     var $engine = '';
  20.  
  21.     /**
  22.      * @var string  type (view, base table, system view)
  23.      */
  24.     var $type = '';
  25.  
  26.     /**
  27.      * @var array   settings
  28.      */
  29.     var $settings = array();
  30.  
  31.     /**
  32.      * @var array errors occured
  33.      */
  34.     var $errors = array();
  35.  
  36.     /**
  37.      * @var array messages
  38.      */
  39.     var $messages = array();
  40.  
  41.     /**
  42.      * Constructor
  43.      *
  44.      * @param   string  $table_name table name
  45.      * @param   string  $db_name    database name
  46.      */
  47.     function __construct($table_name, $db_name)
  48.     {
  49.         $this->setName($table_name);
  50.         $this->setDbName($db_name);
  51.     }
  52.  
  53.     /**
  54.      * @see PMA_Table::getName()
  55.      */
  56.     function __toString()
  57.     {
  58.         return $this->getName();
  59.     }
  60.  
  61.     function getLastError()
  62.     {
  63.         return end($this->errors);
  64.     }
  65.  
  66.     function getLastMessage()
  67.     {
  68.         return end($this->messages);
  69.     }
  70.  
  71.     /**
  72.      * sets table anme
  73.      *
  74.      * @uses    $this->name to set it
  75.      * @param   string  $table_name new table name
  76.      */
  77.     function setName($table_name)
  78.     {
  79.         $this->name = $table_name;
  80.     }
  81.  
  82.     /**
  83.      * returns table name
  84.      *
  85.      * @uses    $this->name as return value
  86.      * @param   boolean wether to quote name with backticks ``
  87.      * @return  string  table name
  88.      */
  89.     function getName($quoted = false)
  90.     {
  91.         if ($quoted) {
  92.             return PMA_backquote($this->name);
  93.         }
  94.         return $this->name;
  95.     }
  96.  
  97.     /**
  98.      * sets database name for this table
  99.      *
  100.      * @uses    $this->db_name  to set it
  101.      * @param   string  $db_name
  102.      */
  103.     function setDbName($db_name)
  104.     {
  105.         $this->db_name = $db_name;
  106.     }
  107.  
  108.     /**
  109.      * returns database name for this table
  110.      *
  111.      * @uses    $this->db_name  as return value
  112.      * @param   boolean wether to quote name with backticks ``
  113.      * @return  string  database name for this table
  114.      */
  115.     function getDbName($quoted = false)
  116.     {
  117.         if ($quoted) {
  118.             return PMA_backquote($this->db_name);
  119.         }
  120.         return $this->db_name;
  121.     }
  122.  
  123.     /**
  124.      * returns full name for table, including database name
  125.      *
  126.      * @param   boolean wether to quote name with backticks ``
  127.      */
  128.     function getFullName($quoted = false)
  129.     {
  130.         return $this->getDbName($quoted) . '.' . $this->getName($quoted);
  131.     }
  132.  
  133.     function isView($db = null, $table = null)
  134.     {
  135.         if (null !== $db && null !== $table) {
  136.             return PMA_Table::_isView($db, $table);
  137.         }
  138.  
  139.         if (strpos($this->get('TABLE TYPE'), 'VIEW')) {
  140.             return true;
  141.         }
  142.  
  143.         return false;
  144.     }
  145.  
  146.     /**
  147.      * sets given $value for given $param
  148.      *
  149.      * @uses    $this->settings to add or change value
  150.      * @param   string  param name
  151.      * @param   mixed   param value
  152.      */
  153.     function set($param, $value)
  154.     {
  155.         $this->settings[$param] = $value;
  156.     }
  157.  
  158.     /**
  159.      * returns value for given setting/param
  160.      *
  161.      * @uses    $this->settings to return value
  162.      * @param   string  name for value to return
  163.      * @return  mixed   value for $param
  164.      */
  165.     function get($param)
  166.     {
  167.         if (isset($this->settings[$param])) {
  168.             return $this->settings[$param];
  169.         }
  170.  
  171.         return null;
  172.     }
  173.  
  174.     /**
  175.      * loads structure data
  176.      */
  177.     function loadStructure()
  178.     {
  179.         $table_info = PMA_DBI_get_tables_full($this->getDbName(), $this->getName());
  180.  
  181.         if (false === $table_info) {
  182.             return false;
  183.         }
  184.  
  185.         $this->settings = $table_info;
  186.  
  187.         if ($this->get('TABLE_ROWS') === null) {
  188.             $this->set('TABLE_ROWS', PMA_Table::countRecords($this->getDbName(),
  189.                 $this->getName(), true, true));
  190.         }
  191.  
  192.         $create_options = explode(' ', $this->get('TABLE_ROWS'));
  193.  
  194.         // export create options by its name as variables into gloabel namespace
  195.         // f.e. pack_keys=1 becomes available as $pack_keys with value of '1'
  196.         foreach ($create_options as $each_create_option) {
  197.             $each_create_option = explode('=', $each_create_option);
  198.             if (isset($each_create_option[1])) {
  199.                 $this->set($$each_create_option[0], $each_create_option[1]);
  200.             }
  201.         }
  202.     }
  203.  
  204.     /**
  205.      * old PHP 4style constructor
  206.      *
  207.      * @see     PMA_Table::__construct()
  208.      */
  209.     function PMA_Table($table_name, $db_name)
  210.     {
  211.         $this->__construct($table_name, $db_name);
  212.     }
  213.  
  214.     /**
  215.      * Checks if this "table" is a view
  216.      *
  217.      * @deprecated
  218.      * @param   string   the database name
  219.      * @param   string   the table name
  220.      *
  221.      * @return  boolean  whether this is a view
  222.      *
  223.      * @access  public
  224.      */
  225.     function _isView($db, $table) {
  226.         // maybe we already know if the table is a view
  227.         // TODO: see what we could do with the possible existence
  228.         // of $table_is_view
  229.         if (isset($GLOBALS['tbl_is_view']) && $GLOBALS['tbl_is_view']) {
  230.             return true;
  231.         }
  232.         // old MySQL version: no view
  233.         if (PMA_MYSQL_INT_VERSION < 50000) {
  234.             return false;
  235.         }
  236.         if (false === PMA_DBI_fetch_value('SELECT TABLE_NAME FROM `information_schema`.`VIEWS` WHERE `TABLE_SCHEMA` = \'' . $db . '\' AND `TABLE_NAME` = \'' . $table . '\';')) {
  237.             return false;
  238.         } else {
  239.             return true;
  240.         }
  241.     }
  242.  
  243.     /**
  244.      * generates column/field specification for ALTER or CREATE TABLE syntax
  245.      *
  246.      * @todo    move into class PMA_Column
  247.      * @static
  248.      * @param   string  $name       name
  249.      * @param   string  $type       type ('INT', 'VARCHAR', 'BIT', ...)
  250.      * @param   string  $length     length ('2', '5,2', '', ...)
  251.      * @param   string  $attribute
  252.      * @param   string  $collation
  253.      * @param   string  $null       with 'NULL' or 'NOT NULL'
  254.      * @param   string  $default    default value
  255.      * @param   boolean $default_current_timestamp  whether default value is
  256.      *                                              CURRENT_TIMESTAMP or not
  257.      *                                              this overrides $default value
  258.      * @param   string  $extra      'AUTO_INCREMENT'
  259.      * @param   string  $comment    field comment
  260.      * @param   array   &$field_primary list of fields for PRIMARY KEY
  261.      * @param   string  $index
  262.      * @param   string  $default_orig
  263.      * @return  string  field specification
  264.      */
  265.     function generateFieldSpec($name, $type, $length = '', $attribute = '',
  266.         $collation = '', $null = false, $default = '',
  267.         $default_current_timestamp = false, $extra = '', $comment = '',
  268.         &$field_primary, $index, $default_orig = false)
  269.     {
  270.  
  271.         // $default_current_timestamp has priority over $default
  272.         // TODO: on the interface, some js to clear the default value
  273.         // when the default current_timestamp is checked
  274.  
  275.         // TODO: include db-name
  276.         $query = PMA_backquote($name) . ' ' . $type;
  277.  
  278.         if ($length != ''
  279.             && !preg_match('@^(DATE|DATETIME|TIME|TINYBLOB|TINYTEXT|BLOB|TEXT|MEDIUMBLOB|MEDIUMTEXT|LONGBLOB|LONGTEXT)$@i', $type)) {
  280.             $query .= '(' . $length . ')';
  281.         }
  282.  
  283.         if ($attribute != '') {
  284.             $query .= ' ' . $attribute;
  285.         }
  286.  
  287.         if (PMA_MYSQL_INT_VERSION >= 40100 && !empty($collation)
  288.           && $collation != 'NULL'
  289.           && preg_match('@^(TINYTEXT|TEXT|MEDIUMTEXT|LONGTEXT|VARCHAR|CHAR|ENUM|SET)$@i', $type)) {
  290.             $query .= PMA_generateCharsetQueryPart($collation);
  291.         }
  292.  
  293.         if ($null !== false) {
  294.             if (!empty($null)) {
  295.                 $query .= ' NOT NULL';
  296.             } else {
  297.                 $query .= ' NULL';
  298.             }
  299.         }
  300.  
  301.         if ($default_current_timestamp
  302.           && strpos(' ' . strtoupper($type), 'TIMESTAMP') == 1) {
  303.             $query .= ' DEFAULT CURRENT_TIMESTAMP';
  304.         // auto_increment field cannot have a default value
  305.         } elseif ($extra !== 'AUTO_INCREMENT'
  306.           && (strlen($default) || $default != $default_orig)) {
  307.             if (strtoupper($default) == 'NULL') {
  308.                 $query .= ' DEFAULT NULL';
  309.             } else {
  310.                 if (strlen($default)) {
  311.                     $query .= ' DEFAULT \'' . PMA_sqlAddslashes($default) . '\'';
  312.                 }
  313.             }
  314.         }
  315.  
  316.         if (!empty($extra)) {
  317.             $query .= ' ' . $extra;
  318.             // An auto_increment field must be use as a primary key
  319.             if ($extra == 'AUTO_INCREMENT' && isset($field_primary)) {
  320.                 $primary_cnt = count($field_primary);
  321.                 for ($j = 0; $j < $primary_cnt && $field_primary[$j] != $index; $j++) {
  322.                     // void
  323.                 } // end for
  324.                 if (isset($field_primary[$j]) && $field_primary[$j] == $index) {
  325.                     $query .= ' PRIMARY KEY';
  326.                     unset($field_primary[$j]);
  327.                 } // end if
  328.             } // end if (auto_increment)
  329.         }
  330.         if (PMA_MYSQL_INT_VERSION >= 40100 && !empty($comment)) {
  331.             $query .= " COMMENT '" . PMA_sqlAddslashes($comment) . "'";
  332.         }
  333.         return $query;
  334.     } // end function
  335.  
  336.     /**
  337.      * Counts and returns (or displays) the number of records in a table
  338.      *
  339.      * Revision 13 July 2001: Patch for limiting dump size from
  340.      * vinay@sanisoft.com & girish@sanisoft.com
  341.      *
  342.      * @param   string   the current database name
  343.      * @param   string   the current table name
  344.      * @param   boolean  whether to retain or to displays the result
  345.      * @param   boolean  whether to force an exact count
  346.      *
  347.      * @return  mixed    the number of records if retain is required, true else
  348.      *
  349.      * @access  public
  350.      */
  351.     function countRecords($db, $table, $ret = false, $force_exact = false)
  352.     {
  353.         $row_count = false;
  354.  
  355.         if (! $force_exact) {
  356.             $row_count = PMA_DBI_fetch_value(
  357.                 'SHOW TABLE STATUS FROM ' . PMA_backquote($db) . ' LIKE \''
  358.                     . PMA_sqlAddslashes($table, true) . '\';',
  359.                 0, 'Rows');
  360.         }
  361.  
  362.         $tbl_is_view = PMA_Table::isView($db, $table);
  363.  
  364.         if (false === $row_count || $row_count < $GLOBALS['cfg']['MaxExactCount']) {
  365.             if (! $tbl_is_view) {
  366.                 $row_count = PMA_DBI_fetch_value(
  367.                     'SELECT COUNT(*) FROM ' . PMA_backquote($db) . '.'
  368.                     . PMA_backquote($table));
  369.             // since counting all rows of a view could be too long
  370.             } else {
  371.                 // try_query because it can fail ( a VIEW was based on
  372.                 // a table that no longer exists)
  373.                 $result = PMA_DBI_try_query(
  374.                     'SELECT 1 FROM ' . PMA_backquote($db) . '.'
  375.                         . PMA_backquote($table) . ' LIMIT '
  376.                         . $GLOBALS['cfg']['MaxExactCount'],
  377.                     null, PMA_DBI_QUERY_STORE);
  378.                 if (!PMA_DBI_getError()) {
  379.                     $row_count = PMA_DBI_num_rows($result);
  380.                     PMA_DBI_free_result($result);
  381.                 }
  382.             }
  383.         }
  384.  
  385.         if ($ret) {
  386.             return $row_count;
  387.         }
  388.  
  389.         /**
  390.          * @deprecated at the moment nowhere is $return = false used
  391.          */
  392.         // Note: as of PMA 2.8.0, we no longer seem to be using
  393.         // PMA_Table::countRecords() in display mode.
  394.         echo PMA_formatNumber($row_count, 0);
  395.         if ($tbl_is_view) {
  396.             echo ' '
  397.                 . sprintf($GLOBALS['strViewMaxExactCount'],
  398.                     $GLOBALS['cfg']['MaxExactCount'],
  399.                     '[a@./Documentation.html#cfg_MaxExactCount@_blank]', '[/a]');
  400.         }
  401.     } // end of the 'PMA_Table::countRecords()' function
  402.  
  403.     /**
  404.      * @TODO    add documentation
  405.      */
  406.     function generateAlter($oldcol, $newcol, $type, $length,
  407.         $attribute, $collation, $null, $default, $default_current_timestamp,
  408.         $extra, $comment='', $default_orig)
  409.     {
  410.         $empty_a = array();
  411.         return PMA_backquote($oldcol) . ' '
  412.             . PMA_Table::generateFieldSpec($newcol, $type, $length, $attribute,
  413.                 $collation, $null, $default, $default_current_timestamp, $extra,
  414.                 $comment, $empty_a, -1, $default_orig);
  415.     } // end function
  416.  
  417.     /**
  418.      * Inserts existing entries in a PMA_* table by reading a value from an old entry
  419.      *
  420.      * @param   string  The array index, which Relation feature to check
  421.      *                  ('relwork', 'commwork', ...)
  422.      * @param   string  The array index, which PMA-table to update
  423.      *                  ('bookmark', 'relation', ...)
  424.      * @param   array   Which fields will be SELECT'ed from the old entry
  425.      * @param   array   Which fields will be used for the WHERE query
  426.      *                  (array('FIELDNAME' => 'FIELDVALUE'))
  427.      * @param   array   Which fields will be used as new VALUES. These are the important
  428.      *                  keys which differ from the old entry.
  429.      *                  (array('FIELDNAME' => 'NEW FIELDVALUE'))
  430.  
  431.      * @global  string  relation variable
  432.      *
  433.      * @author          Garvin Hicking <me@supergarv.de>
  434.      */
  435.     function duplicateInfo($work, $pma_table, $get_fields, $where_fields,
  436.       $new_fields)
  437.     {
  438.         $last_id = -1;
  439.  
  440.         if ($GLOBALS['cfgRelation'][$work]) {
  441.             $select_parts = array();
  442.             $row_fields = array();
  443.             foreach ($get_fields as $get_field) {
  444.                 $select_parts[] = PMA_backquote($get_field);
  445.                 $row_fields[$get_field] = 'cc';
  446.             }
  447.  
  448.             $where_parts = array();
  449.             foreach ($where_fields as $_where => $_value) {
  450.                 $where_parts[] = PMA_backquote($_where) . ' = \''
  451.                     . PMA_sqlAddslashes($_value) . '\'';
  452.             }
  453.  
  454.             $new_parts = array();
  455.             $new_value_parts = array();
  456.             foreach ($new_fields as $_where => $_value) {
  457.                 $new_parts[] = PMA_backquote($_where);
  458.                 $new_value_parts[] = PMA_sqlAddslashes($_value);
  459.             }
  460.  
  461.             $table_copy_query = '
  462.                 SELECT ' . implode(', ', $select_parts) . '
  463.                   FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
  464.                   . PMA_backquote($GLOBALS['cfgRelation'][$pma_table]) . '
  465.                  WHERE ' . implode(' AND ', $where_parts);
  466.  
  467.             // must use PMA_DBI_QUERY_STORE here, since we execute another
  468.             // query inside the loop
  469.             $table_copy_rs    = PMA_query_as_cu($table_copy_query, true,
  470.                 PMA_DBI_QUERY_STORE);
  471.  
  472.             while ($table_copy_row = @PMA_DBI_fetch_assoc($table_copy_rs)) {
  473.                 $value_parts = array();
  474.                 foreach ($table_copy_row as $_key => $_val) {
  475.                     if (isset($row_fields[$_key]) && $row_fields[$_key] == 'cc') {
  476.                         $value_parts[] = PMA_sqlAddslashes($_val);
  477.                     }
  478.                 }
  479.  
  480.                 $new_table_query = '
  481.                     INSERT IGNORE INTO ' . PMA_backquote($GLOBALS['cfgRelation']['db'])
  482.                         . '.' . PMA_backquote($GLOBALS['cfgRelation'][$pma_table]) . '
  483.                     (' . implode(', ', $select_parts) . ',
  484.                      ' . implode(', ', $new_parts) . ')
  485.                     VALUES
  486.                     (\'' . implode('\', \'', $value_parts) . '\',
  487.                      \'' . implode('\', \'', $new_value_parts) . '\')';
  488.  
  489.                 PMA_query_as_cu($new_table_query);
  490.                 $last_id = PMA_DBI_insert_id();
  491.             } // end while
  492.  
  493.             PMA_DBI_free_result($table_copy_rs);
  494.  
  495.             return $last_id;
  496.         }
  497.  
  498.         return true;
  499.     } // end of 'PMA_Table::duplicateInfo()' function
  500.  
  501.  
  502.     /**
  503.      * Copies or renames table
  504.      * FIXME: use RENAME for move operations
  505.      *        - would work only if the databases are on the same filesystem,
  506.      *          how can we check that? try the operation and
  507.      *          catch an error? 
  508.      *        - for views, only if MYSQL > 50013
  509.      *        - still have to handle pmadb synch.
  510.      *
  511.      * @author          Michal Cihar <michal@cihar.com>
  512.      */
  513.     function moveCopy($source_db, $source_table, $target_db, $target_table, $what, $move, $mode)
  514.     {
  515.         global $dblist, $err_url;
  516.  
  517.         if (! isset($GLOBALS['sql_query'])) {
  518.             $GLOBALS['sql_query'] = '';
  519.         }
  520.  
  521.         // set export settings we need
  522.         $GLOBALS['sql_backquotes'] = 1;
  523.         $GLOBALS['asfile']         = 1;
  524.  
  525.         // Ensure the target is valid
  526.         if (count($dblist) > 0 &&
  527.           (! in_array($source_db, $dblist) || ! in_array($target_db, $dblist))) {
  528.               // TODO exit really needed here? or just a return?
  529.             exit;
  530.         }
  531.  
  532.         $source = PMA_backquote($source_db) . '.' . PMA_backquote($source_table);
  533.         if (! isset($target_db) || ! strlen($target_db)) {
  534.             $target_db = $source_db;
  535.         }
  536.  
  537.         // Doing a select_db could avoid some problems with replicated databases,
  538.         // when moving table from replicated one to not replicated one
  539.         PMA_DBI_select_db($target_db);
  540.  
  541.         $target = PMA_backquote($target_db) . '.' . PMA_backquote($target_table);
  542.  
  543.         // do not create the table if dataonly
  544.         if ($what != 'dataonly') {
  545.             require_once './libraries/export/sql.php';
  546.  
  547.             $no_constraints_comments = true;
  548.         $GLOBALS['sql_constraints_query'] = '';
  549.  
  550.             $sql_structure = PMA_getTableDef($source_db, $source_table, "\n", $err_url);
  551.             unset($no_constraints_comments);
  552.             $parsed_sql =  PMA_SQP_parse($sql_structure);
  553.             $analyzed_sql = PMA_SQP_analyze($parsed_sql);
  554.             $i = 0;
  555.             if (empty($analyzed_sql[0]['create_table_fields'])) {
  556.             // this is not a CREATE TABLE, so find the first VIEW
  557.                 $target_for_view = PMA_backquote($target_db);
  558.                 while (true) {
  559.                 if ($parsed_sql[$i]['type'] == 'alpha_reservedWord' && $parsed_sql[$i]['data'] == 'VIEW') {
  560.                         break;
  561.                     }
  562.                     $i++;
  563.                 }
  564.             }
  565.             unset($analyzed_sql);
  566.  
  567.             /* nijel: Find table name in query and replace it */
  568.             while ($parsed_sql[$i]['type'] != 'quote_backtick') {
  569.                 $i++;
  570.             }
  571.  
  572.             /* no need to PMA_backquote() */
  573.         if (isset($target_for_view)) {
  574.         // this a view definition; we just found the first db name
  575.         // that follows DEFINER VIEW
  576.         // so change it for the new db name
  577.                 $parsed_sql[$i]['data'] = $target_for_view;
  578.         // then we have to find all references to the source db 
  579.         // and change them to the target db, ensuring we stay into
  580.         // the $parsed_sql limits
  581.         $last = $parsed_sql['len'] - 1;
  582.         $backquoted_source_db = PMA_backquote($source_db);
  583.         for (++$i; $i <= $last; $i++) { 
  584.                     if ($parsed_sql[$i]['type'] == 'quote_backtick' && $parsed_sql[$i]['data'] == $backquoted_source_db) {
  585.                         $parsed_sql[$i]['data'] = $target_for_view;
  586.             }
  587.         }
  588.         unset($last,$backquoted_source_db);
  589.             } else {
  590.                 $parsed_sql[$i]['data'] = $target;
  591.             }
  592.  
  593.             /* Generate query back */
  594.             $sql_structure = PMA_SQP_formatHtml($parsed_sql, 'query_only');
  595.             // If table exists, and 'add drop table' is selected: Drop it!
  596.             $drop_query = '';
  597.             if (isset($GLOBALS['drop_if_exists'])
  598.               && $GLOBALS['drop_if_exists'] == 'true') {
  599.                 if (PMA_Table::_isView($target_db,$target_table)) {
  600.                     $drop_query = 'DROP VIEW';
  601.                 } else {
  602.                     $drop_query = 'DROP TABLE';
  603.                 }
  604.                 $drop_query .= ' IF EXISTS '
  605.                     . PMA_backquote($target_db) . '.'
  606.                     . PMA_backquote($target_table);
  607.                 PMA_DBI_query($drop_query);
  608.  
  609.                 $GLOBALS['sql_query'] .= "\n" . $drop_query . ';';
  610.  
  611.                 // garvin: If an existing table gets deleted, maintain any
  612.                 // entries for the PMA_* tables
  613.                 $maintain_relations = true;
  614.             }
  615.  
  616.             @PMA_DBI_query($sql_structure);
  617.             $GLOBALS['sql_query'] .= "\n" . $sql_structure . ';';
  618.  
  619.             if (($move || isset($GLOBALS['add_constraints']))
  620.               && !empty($GLOBALS['sql_constraints_query'])) {
  621.                 $parsed_sql =  PMA_SQP_parse($GLOBALS['sql_constraints_query']);
  622.                 $i = 0;
  623.  
  624.                 // find the first quote_backtick, it must be the source table name
  625.                 while ($parsed_sql[$i]['type'] != 'quote_backtick') {
  626.                     $i++;
  627.             // maybe someday we should guard against going over limit
  628.                     //if ($i == $parsed_sql['len']) {
  629.                     //    break;
  630.                     //}
  631.                 }
  632.  
  633.                 // replace it by the target table name, no need to PMA_backquote()
  634.                 $parsed_sql[$i]['data'] = $target;
  635.  
  636.                 // now we must remove all quote_backtick that follow a CONSTRAINT
  637.                 // keyword, because a constraint name must be unique in a db
  638.  
  639.                 $cnt = $parsed_sql['len'] - 1;
  640.  
  641.                 for ($j = $i; $j < $cnt; $j++) {
  642.                     if ($parsed_sql[$j]['type'] == 'alpha_reservedWord'
  643.                       && strtoupper($parsed_sql[$j]['data']) == 'CONSTRAINT') {
  644.                         if ($parsed_sql[$j+1]['type'] == 'quote_backtick') {
  645.                             $parsed_sql[$j+1]['data'] = '';
  646.                         }
  647.                     }
  648.                 }
  649.  
  650.                 // Generate query back
  651.                 $GLOBALS['sql_constraints_query'] = PMA_SQP_formatHtml($parsed_sql,
  652.                     'query_only');
  653.             if ($mode == 'one_table') {
  654.                     PMA_DBI_query($GLOBALS['sql_constraints_query']);
  655.         }
  656.                 $GLOBALS['sql_query'] .= "\n" . $GLOBALS['sql_constraints_query'];
  657.             if ($mode == 'one_table') {
  658.                     unset($GLOBALS['sql_constraints_query']);
  659.         }
  660.             }
  661.  
  662.         } else {
  663.             $GLOBALS['sql_query'] = '';
  664.         }
  665.  
  666.         // Copy the data unless this is a VIEW
  667.         if (($what == 'data' || $what == 'dataonly') && ! PMA_Table::_isView($target_db,$target_table)) {
  668.             $sql_insert_data =
  669.                 'INSERT INTO ' . $target . ' SELECT * FROM ' . $source;
  670.             PMA_DBI_query($sql_insert_data);
  671.             $GLOBALS['sql_query']      .= "\n\n" . $sql_insert_data . ';';
  672.         }
  673.  
  674.         require_once './libraries/relation.lib.php';
  675.         $GLOBALS['cfgRelation'] = PMA_getRelationsParam();
  676.  
  677.         // Drops old table if the user has requested to move it
  678.         if ($move) {
  679.  
  680.             // This could avoid some problems with replicated databases, when
  681.             // moving table from replicated one to not replicated one
  682.             PMA_DBI_select_db($source_db);
  683.  
  684.             if (PMA_Table::_isView($source_db,$source_table)) {
  685.                 $sql_drop_query = 'DROP VIEW';
  686.             } else {
  687.                 $sql_drop_query = 'DROP TABLE';
  688.             }
  689.             $sql_drop_query .= ' ' . $source;
  690.             PMA_DBI_query($sql_drop_query);
  691.  
  692.             // garvin: Move old entries from PMA-DBs to new table
  693.             if ($GLOBALS['cfgRelation']['commwork']) {
  694.                 $remove_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['column_info'])
  695.                               . ' SET     table_name = \'' . PMA_sqlAddslashes($target_table) . '\', '
  696.                               . '        db_name    = \'' . PMA_sqlAddslashes($target_db) . '\''
  697.                               . ' WHERE db_name  = \'' . PMA_sqlAddslashes($source_db) . '\''
  698.                               . ' AND table_name = \'' . PMA_sqlAddslashes($source_table) . '\'';
  699.                 PMA_query_as_cu($remove_query);
  700.                 unset($remove_query);
  701.             }
  702.  
  703.             // garvin: updating bookmarks is not possible since only a single table is moved,
  704.             // and not the whole DB.
  705.  
  706.             if ($GLOBALS['cfgRelation']['displaywork']) {
  707.                 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['table_info'])
  708.                                 . ' SET     db_name = \'' . PMA_sqlAddslashes($target_db) . '\', '
  709.                                 . '         table_name = \'' . PMA_sqlAddslashes($target_table) . '\''
  710.                                 . ' WHERE db_name  = \'' . PMA_sqlAddslashes($source_db) . '\''
  711.                                 . ' AND table_name = \'' . PMA_sqlAddslashes($source_table) . '\'';
  712.                 PMA_query_as_cu($table_query);
  713.                 unset($table_query);
  714.             }
  715.  
  716.             if ($GLOBALS['cfgRelation']['relwork']) {
  717.                 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['relation'])
  718.                                 . ' SET     foreign_table = \'' . PMA_sqlAddslashes($target_table) . '\','
  719.                                 . '         foreign_db = \'' . PMA_sqlAddslashes($target_db) . '\''
  720.                                 . ' WHERE foreign_db  = \'' . PMA_sqlAddslashes($source_db) . '\''
  721.                                 . ' AND foreign_table = \'' . PMA_sqlAddslashes($source_table) . '\'';
  722.                 PMA_query_as_cu($table_query);
  723.                 unset($table_query);
  724.  
  725.                 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['relation'])
  726.                                 . ' SET     master_table = \'' . PMA_sqlAddslashes($target_table) . '\','
  727.                                 . '         master_db = \'' . PMA_sqlAddslashes($target_db) . '\''
  728.                                 . ' WHERE master_db  = \'' . PMA_sqlAddslashes($source_db) . '\''
  729.                                 . ' AND master_table = \'' . PMA_sqlAddslashes($source_table) . '\'';
  730.                 PMA_query_as_cu($table_query);
  731.                 unset($table_query);
  732.             }
  733.  
  734.             // garvin: [TODO] Can't get moving PDFs the right way. The page numbers always
  735.             // get screwed up independently from duplication because the numbers do not
  736.             // seem to be stored on a per-database basis. Would the author of pdf support
  737.             // please have a look at it?
  738.  
  739.             if ($GLOBALS['cfgRelation']['pdfwork']) {
  740.                 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['table_coords'])
  741.                                 . ' SET     table_name = \'' . PMA_sqlAddslashes($target_table) . '\','
  742.                                 . '         db_name = \'' . PMA_sqlAddslashes($target_db) . '\''
  743.                                 . ' WHERE db_name  = \'' . PMA_sqlAddslashes($source_db) . '\''
  744.                                 . ' AND table_name = \'' . PMA_sqlAddslashes($source_table) . '\'';
  745.                 PMA_query_as_cu($table_query);
  746.                 unset($table_query);
  747.                 /*
  748.                 $pdf_query = 'SELECT pdf_page_number '
  749.                            . ' FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['table_coords'])
  750.                            . ' WHERE db_name  = \'' . PMA_sqlAddslashes($target_db) . '\''
  751.                            . ' AND table_name = \'' . PMA_sqlAddslashes($target_table) . '\'';
  752.                 $pdf_rs = PMA_query_as_cu($pdf_query);
  753.  
  754.                 while ($pdf_copy_row = PMA_DBI_fetch_assoc($pdf_rs)) {
  755.                     $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['pdf_pages'])
  756.                                     . ' SET     db_name = \'' . PMA_sqlAddslashes($target_db) . '\''
  757.                                     . ' WHERE db_name  = \'' . PMA_sqlAddslashes($source_db) . '\''
  758.                                     . ' AND page_nr = \'' . PMA_sqlAddslashes($pdf_copy_row['pdf_page_number']) . '\'';
  759.                     $tb_rs    = PMA_query_as_cu($table_query);
  760.                     unset($table_query);
  761.                     unset($tb_rs);
  762.                 }
  763.                 */
  764.             }
  765.  
  766.             $GLOBALS['sql_query']      .= "\n\n" . $sql_drop_query . ';';
  767.         } else {
  768.             // garvin: Create new entries as duplicates from old PMA DBs
  769.             if ($what != 'dataonly' && !isset($maintain_relations)) {
  770.                 if ($GLOBALS['cfgRelation']['commwork']) {
  771.                     // Get all comments and MIME-Types for current table
  772.                     $comments_copy_query = 'SELECT
  773.                                                 column_name, ' . PMA_backquote('comment') . ($GLOBALS['cfgRelation']['mimework'] ? ', mimetype, transformation, transformation_options' : '') . '
  774.                                             FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['column_info']) . '
  775.                                             WHERE
  776.                                                 db_name = \'' . PMA_sqlAddslashes($source_db) . '\' AND
  777.                                                 table_name = \'' . PMA_sqlAddslashes($source_table) . '\'';
  778.                     $comments_copy_rs    = PMA_query_as_cu($comments_copy_query);
  779.  
  780.                     // Write every comment as new copied entry. [MIME]
  781.                     while ($comments_copy_row = PMA_DBI_fetch_assoc($comments_copy_rs)) {
  782.                         $new_comment_query = 'REPLACE INTO ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['column_info'])
  783.                                     . ' (db_name, table_name, column_name, ' . PMA_backquote('comment') . ($GLOBALS['cfgRelation']['mimework'] ? ', mimetype, transformation, transformation_options' : '') . ') '
  784.                                     . ' VALUES('
  785.                                     . '\'' . PMA_sqlAddslashes($target_db) . '\','
  786.                                     . '\'' . PMA_sqlAddslashes($target_table) . '\','
  787.                                     . '\'' . PMA_sqlAddslashes($comments_copy_row['column_name']) . '\''
  788.                                     . ($GLOBALS['cfgRelation']['mimework'] ? ',\'' . PMA_sqlAddslashes($comments_copy_row['comment']) . '\','
  789.                                             . '\'' . PMA_sqlAddslashes($comments_copy_row['mimetype']) . '\','
  790.                                             . '\'' . PMA_sqlAddslashes($comments_copy_row['transformation']) . '\','
  791.                                             . '\'' . PMA_sqlAddslashes($comments_copy_row['transformation_options']) . '\'' : '')
  792.                                     . ')';
  793.                         PMA_query_as_cu($new_comment_query);
  794.                     } // end while
  795.                     PMA_DBI_free_result($comments_copy_rs);
  796.                     unset($comments_copy_rs);
  797.                 }
  798.  
  799.                 // duplicating the bookmarks must not be done here, but
  800.                 // just once per db
  801.  
  802.                 $get_fields = array('display_field');
  803.                 $where_fields = array('db_name' => $source_db, 'table_name' => $source_table);
  804.                 $new_fields = array('db_name' => $target_db, 'table_name' => $target_table);
  805.                 PMA_Table::duplicateInfo('displaywork', 'table_info', $get_fields, $where_fields, $new_fields);
  806.  
  807.                 $get_fields = array('master_field', 'foreign_db', 'foreign_table', 'foreign_field');
  808.                 $where_fields = array('master_db' => $source_db, 'master_table' => $source_table);
  809.                 $new_fields = array('master_db' => $target_db, 'master_table' => $target_table);
  810.                 PMA_Table::duplicateInfo('relwork', 'relation', $get_fields, $where_fields, $new_fields);
  811.  
  812.                 $get_fields = array('foreign_field', 'master_db', 'master_table', 'master_field');
  813.                 $where_fields = array('foreign_db' => $source_db, 'foreign_table' => $source_table);
  814.                 $new_fields = array('foreign_db' => $target_db, 'foreign_table' => $target_table);
  815.                 PMA_Table::duplicateInfo('relwork', 'relation', $get_fields, $where_fields, $new_fields);
  816.  
  817.                 // garvin: [TODO] Can't get duplicating PDFs the right way. The page numbers always
  818.                 // get screwed up independently from duplication because the numbers do not
  819.                 // seem to be stored on a per-database basis. Would the author of pdf support
  820.                 // please have a look at it?
  821.                 /*
  822.                 $get_fields = array('page_descr');
  823.                 $where_fields = array('db_name' => $source_db);
  824.                 $new_fields = array('db_name' => $target_db);
  825.                 $last_id = PMA_Table::duplicateInfo('pdfwork', 'pdf_pages', $get_fields, $where_fields, $new_fields);
  826.  
  827.                 if (isset($last_id) && $last_id >= 0) {
  828.                     $get_fields = array('x', 'y');
  829.                     $where_fields = array('db_name' => $source_db, 'table_name' => $source_table);
  830.                     $new_fields = array('db_name' => $target_db, 'table_name' => $target_table, 'pdf_page_number' => $last_id);
  831.                     PMA_Table::duplicateInfo('pdfwork', 'table_coords', $get_fields, $where_fields, $new_fields);
  832.                 }
  833.                 */
  834.             }
  835.         }
  836.  
  837.     }
  838.  
  839.     /**
  840.      * checks if given name is a valid table name,
  841.      * currently if not empty, trailing spaces, '.', '/' and '\'
  842.      *
  843.      * @todo    add check for valid chars in filename on current system/os
  844.      * @see     http://dev.mysql.com/doc/refman/5.0/en/legal-names.html
  845.      * @param   string  $table_name name to check
  846.      * @return  boolean whether the string is valid or not
  847.      */
  848.     function isValidName($table_name)
  849.     {
  850.         if ($table_name !== trim($table_name)) {
  851.             // trailing spaces
  852.             return false;
  853.         }
  854.  
  855.         if (! strlen($table_name)) {
  856.             // zero length
  857.             return false;
  858.         }
  859.  
  860.         if (preg_match('/[.\/\\\\]+/i', $table_name)) {
  861.             // illegal char . / \
  862.             return false;
  863.         }
  864.  
  865.         return true;
  866.     }
  867.  
  868.     /**
  869.      * renames table
  870.      *
  871.      * @param   string  new table name
  872.      * @param   string  new database name
  873.      * @return  boolean success
  874.      */
  875.     function rename($new_name, $new_db = null)
  876.     {
  877.         if (null !== $new_db && $new_db !== $this->getDbName()) {
  878.             // Ensure the target is valid
  879.             if (count($GLOBALS['dblist']) > 0
  880.               && ! in_array($new_db, $GLOBALS['dblist'])) {
  881.                 $this->errors[] = $GLOBALS['strInvalidDatabase'] . ': ' . $new_db;
  882.                 return false;
  883.             }
  884.         } else {
  885.             $new_db = $this->getDbName();
  886.         }
  887.  
  888.         $new_table = new PMA_Table($new_name, $new_db);
  889.  
  890.         if ($this->getFullName() === $new_table->getFullName()) {
  891.             return true;
  892.         }
  893.  
  894.         if (! PMA_Table::isValidName($new_name)) {
  895.             $this->errors[] = $GLOBALS['strInvalidTableName'] . ': ' . $new_table->getFullName();
  896.             return false;
  897.         }
  898.  
  899.         $GLOBALS['sql_query'] = '
  900.             RENAME TABLE ' . $this->getFullName(true) . '
  901.                       TO ' . $new_table->getFullName(true) . ';';
  902.         if (! PMA_DBI_query($GLOBALS['sql_query'])) {
  903.             $this->errors[] = sprintf($GLOBALS['strErrorRenamingTable'], $this->getFullName(), $new_table->getFullName());
  904.             return false;
  905.         }
  906.  
  907.         $old_name = $this->getName();
  908.         $old_db = $this->getDbName();
  909.         $this->setName($new_name);
  910.         $this->setDbName($new_db);
  911.  
  912.         // TODO move into extra function
  913.         // PMA_Relation::renameTable($new_name, $old_name, $new_db, $old_db)
  914.         // garvin: Move old entries from comments to new table
  915.         require_once './libraries/relation.lib.php';
  916.         $GLOBALS['cfgRelation'] = PMA_getRelationsParam();
  917.         if ($GLOBALS['cfgRelation']['commwork']) {
  918.             $remove_query = '
  919.                 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
  920.                     . PMA_backquote($GLOBALS['cfgRelation']['column_info']) . '
  921.                    SET `db_name`    = \'' . PMA_sqlAddslashes($new_db) . '\',
  922.                        `table_name` = \'' . PMA_sqlAddslashes($new_name) . '\'
  923.                  WHERE `db_name`    = \'' . PMA_sqlAddslashes($old_db) . '\'
  924.                    AND `table_name` = \'' . PMA_sqlAddslashes($old_name) . '\'';
  925.             PMA_query_as_cu($remove_query);
  926.             unset($remove_query);
  927.         }
  928.  
  929.         if ($GLOBALS['cfgRelation']['displaywork']) {
  930.             $table_query = '
  931.                 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
  932.                     . PMA_backquote($GLOBALS['cfgRelation']['table_info']) . '
  933.                    SET `db_name`    = \'' . PMA_sqlAddslashes($new_db) . '\',
  934.                        `table_name` = \'' . PMA_sqlAddslashes($new_name) . '\'
  935.                  WHERE `db_name`    = \'' . PMA_sqlAddslashes($old_db) . '\'
  936.                    AND `table_name` = \'' . PMA_sqlAddslashes($old_name) . '\'';
  937.             PMA_query_as_cu($table_query);
  938.             unset($table_query);
  939.         }
  940.  
  941.         if ($GLOBALS['cfgRelation']['relwork']) {
  942.             $table_query = '
  943.                 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
  944.                     . PMA_backquote($GLOBALS['cfgRelation']['relation']) . '
  945.                    SET `foreign_db`    = \'' . PMA_sqlAddslashes($new_db) . '\',
  946.                        `foreign_table` = \'' . PMA_sqlAddslashes($new_name) . '\'
  947.                  WHERE `foreign_db`    = \'' . PMA_sqlAddslashes($old_db) . '\'
  948.                    AND `foreign_table` = \'' . PMA_sqlAddslashes($old_name) . '\'';
  949.             PMA_query_as_cu($table_query);
  950.  
  951.             $table_query = '
  952.                 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
  953.                     . PMA_backquote($GLOBALS['cfgRelation']['relation']) . '
  954.                    SET `master_db`    = \'' . PMA_sqlAddslashes($new_db) . '\',
  955.                        `master_table` = \'' . PMA_sqlAddslashes($new_name) . '\'
  956.                  WHERE `master_db`    = \'' . PMA_sqlAddslashes($old_db) . '\'
  957.                    AND `master_table` = \'' . PMA_sqlAddslashes($old_name) . '\'';
  958.             PMA_query_as_cu($table_query);
  959.             unset($table_query);
  960.         }
  961.  
  962.         if ($GLOBALS['cfgRelation']['pdfwork']) {
  963.             $table_query = '
  964.                 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
  965.                     . PMA_backquote($GLOBALS['cfgRelation']['table_coords']) . '
  966.                    SET `db_name`    = \'' . PMA_sqlAddslashes($new_db) . '\',
  967.                        `table_name` = \'' . PMA_sqlAddslashes($new_name) . '\'
  968.                  WHERE `db_name`    = \'' . PMA_sqlAddslashes($old_db) . '\'
  969.                    AND `table_name` = \'' . PMA_sqlAddslashes($old_name) . '\'';
  970.             PMA_query_as_cu($table_query);
  971.             unset($table_query);
  972.         }
  973.  
  974.         $this->messages[] = sprintf($GLOBALS['strRenameTableOK'],
  975.             htmlspecialchars($old_name), htmlspecialchars($new_name));
  976.         return true;
  977.     }
  978. }
  979. ?>
  980.